package com.jl15988.simpletools.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jl15988.simpletools.system.domain.entity.OperationLog;
import com.jl15988.simpletools.system.mapper.OperationLogMapper;
import com.jl15988.simpletools.system.service.OperationLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 操作日志服务实现类
 *
 * @author jl15988
 */
@Slf4j
@Service
public class OperationLogServiceImpl extends ServiceImpl<OperationLogMapper, OperationLog> implements OperationLogService {

    @Override
    public boolean addLog(Long userId, String operationType, Long targetId, String detail) {
        OperationLog operationLog = new OperationLog();
        operationLog.setUserId(userId);
        operationLog.setOperationType(operationType);
        operationLog.setTargetId(targetId);
        operationLog.setDetail(detail);
        operationLog.setCreatedAt(LocalDateTime.now());
        return this.save(operationLog);
    }

    @Override
    public IPage<OperationLog> getLogPage(int page, int size, Long userId, String operationType, String startTime, String endTime) {
        // 构建查询条件
        LambdaQueryWrapper<OperationLog> queryWrapper = new LambdaQueryWrapper<>();
        if (userId != null) {
            queryWrapper.eq(OperationLog::getUserId, userId);
        }
        if (StrUtil.isNotBlank(operationType)) {
            queryWrapper.eq(OperationLog::getOperationType, operationType);
        }

        // 处理时间范围
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (StrUtil.isNotBlank(startTime)) {
            LocalDateTime startDateTime = LocalDateTime.parse(startTime, formatter);
            queryWrapper.ge(OperationLog::getCreatedAt, startDateTime);
        }
        if (StrUtil.isNotBlank(endTime)) {
            LocalDateTime endDateTime = LocalDateTime.parse(endTime, formatter);
            queryWrapper.le(OperationLog::getCreatedAt, endDateTime);
        }

        // 按时间倒序排序
        queryWrapper.orderByDesc(OperationLog::getCreatedAt);

        // 分页查询
        Page<OperationLog> pageParam = new Page<>(page, size);
        return this.page(pageParam, queryWrapper);
    }
} 